package com.tpvlog.im.common;

public class ZkWatcherDemo {

public void testNodeCache() {
    String workerPath = "/test/listener/remoteNode";
    String subWorkerPath = "/test/listener/remoteNode/id-";
    boolean isExist = ZKclient.instance.isNodeExist(workerPath);
    if (!isExist) {
        ZKclient.instance.createNode(workerPath, null);
    }
    CuratorFramework client = ZKclient.instance.getClient();
    try {
        TreeCache treeCache = new TreeCache(client, workerPath);
        TreeCacheListener listener = new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) {
                try {
                    ChildData data = event.getData();
                    if (data == null) {
                        log.info("数据为空");
                        return;
                    }
                    switch (event.getType()) {
                        case NODE_ADDED:
                            log.info("[TreeCache]节点增加, path={}, data={}",
                                    data.getPath(), new String(data.getData(),
                                            "UTF-8"));
                            break;
                        case NODE_UPDATED:
                            log.info("[TreeCache]节点更新, path={}, data={}",
                                    data.getPath(), new String(data.getData(),
                                            "UTF-8"));
                            break;
                        case NODE_REMOVED:
                            log.info("[TreeCache]节点删除, path={}, data={}",
                                    data.getPath(), new String(data.getData(),
                                            "UTF-8"));
                            break;
                        default:
                            break;
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        };
        treeCache.getListenable().addListener(listener);
        // 启动缓存视图
        treeCache.start();
        Thread.sleep(1000);
        // 创建3个子节点
        for (int i = 0; i < 3; i++) {
            ZKclient.instance.createNode(subWorkerPath + i, null);
        }
        Thread.sleep(1000);
        // 删除3个子节点
        for (int i = 0; i < 3; i++) {
            ZKclient.instance.deleteNode(subWorkerPath + i);
        }
        Thread.sleep(1000);
        // 删除当前节点
        ZKclient.instance.deleteNode(workerPath);
        Thread.sleep(Integer.MAX_VALUE);
    } catch (Exception e) {
        log.error("PathCache监听失败, path=", workerPath);
    }
}
}